package qingxin.servlet.client.photo;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONObject;

import qingxin.dao.AlbumDAO;
import qingxin.dao.PhotoDAO;
import qingxin.factory.DAOFactory;
import qingxin.vo.Album;

@WebServlet("/client/album/getAll")
public class AlbumsServlet extends HttpServlet{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private PhotoDAO photoDAO;
	private AlbumDAO albumDAO;
	public AlbumsServlet(){
		super();
		photoDAO = DAOFactory.getPhotoDAO();
		albumDAO = DAOFactory.getAlbumDAO();
	}
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
    throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
    	response.setContentType("text/html; charset=utf-8");
    	response.setCharacterEncoding("utf-8");
		PrintWriter writer = response.getWriter();
		
		try{
			String limitS = request.getParameter("limit");
			int limit = (limitS == null) ? 20 : Integer.parseInt(limitS);
			String startS = request.getParameter("start");
			int start = (startS == null) ? Integer.MAX_VALUE : Integer.parseInt(startS);
			
			JSONObject jsonResult = new JSONObject();
			JSONArray jsonAlbums = new JSONArray();
			Album[] albums = albumDAO.getAll(start, limit);
			for(Album album : albums){
				JSONObject jsonAlbum = new JSONObject();
				jsonAlbum.put("id", album.getAlbumID());
				String cover = photoDAO.getByID(album.getCoverID()).getOriginalAddress();
				jsonAlbum.put("cover",cover);
				jsonAlbum.put("name", album.getName());
				jsonAlbum.put("introduction", album.getIntroduction());
				
				jsonAlbums.put(jsonAlbum);
			}
			
			jsonResult.put("albums", jsonAlbums);
			
			writer.println(jsonResult.toString());
			
			response.setStatus(HttpServletResponse.SC_OK);
		}
		catch(Exception e){
			response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
			writer.println("{\"msg\":\"wrong\"}");
		}
		finally{
			writer.flush();
			writer.close();
		}
	}
}
